//
// StoreNuke.Net -  http://www.storenuke.net
// Copyright (c) 2005
// by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http://www.willowtreesoftware.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Web.UI.WebControls;
using StoreNuke.StarterKit.Commerce;
//namespace WillowTreeSoftware.Authorize.Net.Gateway
//{
	/// <summary>
	///		Summary description for gateway.
	/// </summary>
	public class gateway : GatewayControl
	{
		protected Label lblMessage;
		protected Label lblCard;
		protected Label lblNumber;
		protected Label lblName;
		protected Label lblDate;
		protected Label lblValidationNumber;
		protected RadioButtonList rbCard;
		protected TextBox txtNumber;
		protected TextBox txtName;
		protected DropDownList ddlMonth;
		protected DropDownList ddlYear;
		protected Button btnCheckout;
		protected LinkButton btnEditSettings;
		protected LinkButton btnSave;
		protected Label lblGateway;
		protected Label lblVersion;
		protected Label lblUsername;
		protected Label lblPassword;
		protected Label lblCapture;
		protected Label lblTest;
		protected TextBox txtGateway;
		protected TextBox txtVersion;
		protected TextBox txtUsername;
		protected TextBox txtPassword;
		protected DropDownList ddlCapture;
		protected CheckBox cbTest;
		protected Panel pnAdmin;
		protected TextBox txtVer;
		protected Panel pnCardInfo;
		protected RequiredFieldValidator rfvCard;
		protected RequiredFieldValidator rfvName;
		protected RequiredFieldValidator rfvNumber;
		protected RequiredFieldValidator rfvVer;

		StoreControlsDB store = new StoreControlsDB();
		protected System.Web.UI.WebControls.Label lblSlash;
		
		Hashtable settings = new Hashtable();

		private void Page_Load(object sender, EventArgs e)
		{
			settings = store.GetStoreControlSettings(StoreControlID);
			if(! Page.IsPostBack)
			{
				LoadAdmin();
				for(int i = 0 ; i < 10 ; i++)
				{
					ddlYear.Items.Add(DateTime.Now.AddYears(i).ToShortDateString().Substring(DateTime.Now.AddYears(i).ToShortDateString().Length - 2));
				}

				//If Cart is a 0 value, allow checkout without charg...
				if(Convert.ToDecimal(CheckOut.Total) == Convert.ToDecimal(0))
				{
					pnCardInfo.Visible = false;
				}
				else
				{
					pnCardInfo.Visible = true;
				}
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnCheckout.Click += new System.EventHandler(this.btnCheckout_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnCheckout_Click(object sender, EventArgs e)
		{
			CartProcessingControl ct = new CartProcessingControl();
			if((Convert.ToDecimal(CheckOut.Total) == Convert.ToDecimal(0)) || (ChargeCard()))
			{
				int returnValue = ct.ProcessCart(Convert.ToInt32(CheckOut.ShipToAddress),Context.User.Identity.Name);
				if(returnValue > -1)
				{
					CheckOut.CartMessage = "Your order was completed successfully.<br><br>Your order number is: " + returnValue;
					btnCheckout.Visible = false;
					CheckOut.HidePaymentPanel = true;
				}	
				else
				{
					lblMessage.Text = "Error Processing Cart";
				}
			}
		}

		private bool ChargeCard()
		{
			AuthNetPaymentAuth auth = new AuthNetPaymentAuth();
			string[] authReturn = auth.RequestAuth(
				txtName.Text.Substring(0,txtName.Text.IndexOf(" ")),
				txtName.Text.Substring(txtName.Text.LastIndexOf(" ")),"",
				CheckOut.BillingAddress.Address1 + " " + CheckOut.BillingAddress.Address2,
				CheckOut.BillingAddress.City,
				CheckOut.BillingAddress.Region,
				CheckOut.BillingAddress.PostalCode,
				CheckOut.BillingAddress.Phone1,
				CheckOut.Total,
				txtNumber.Text,
				txtVer.Text,
				ddlMonth.SelectedValue,
				ddlYear.SelectedValue,
				"False",
				Context.User.Identity.Name,
				settings["WTAuthNetGateway"].ToString(),
				settings["WTAuthNetVersion"].ToString(),
				settings["WTAuthNetTest"].ToString(),
				settings["WTAuthNetUsername"].ToString(),
				settings["WTAuthNetPassword"].ToString(),
				settings["WTAuthNetCapture"].ToString()); 

			if(authReturn[0] == "1")
			{
				CheckOut.HidePaymentPanel = true;
				return true;
			}else
			{
				lblMessage.Text = authReturn[3];
				return false;
			}
		}

		private void LoadAdmin()
		{
			if(settings["WTAuthNetGateway"] == null)
			{
				lblMessage.Text = "Gateway not yet configured.  You cannot checkout!";
				pnCardInfo.Visible = false;
				btnCheckout.Visible = false;
			}
			else
			{
				lblMessage.Text = "";
				pnCardInfo.Visible = true;
				btnCheckout.Visible = true;
			}
		}
	}
//}
